﻿using Module_Debug.Hardware;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug
{
    public partial class VTDR6110C_ZCQ : Form
    {
        /// <summary>
        /// 请搜索   需要修改   适配新IC（IC名称要全局替换），本注释只适用于代码中的函数、变量修改部分
        /// </summary>
        frmMain frmTop = null;
        CaSDK CaSDKObj = new CaSDK();//410
        CRC16 CRCData = new CRC16();//CRC
        public static bool firstGammaFlag = true;   //初次打开子窗体标志位
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke
        private bool Listening = false;//是否没有执行完invoke相关操作   
        private List<byte> buffer = new List<byte>(4096);//默认分配1/16页内存，并始终限制不允许超过
        private byte[] Rec_tmp = new byte[1];
        ArrayList GAMMA_message_save = new ArrayList();//用于保存listview数据时用的数组
        private int Multi_gamma_txt_now_index = 0;//当前调试gamma序号（组）
        private int Multi_gamma_txt_next_index;
        private int Multi_gamma_txt_line_count = 0;
        private int Multi_gamma_group_index = 0;
        List<Setting.Gamma_Property> Diven_Gamma = new List<Setting.Gamma_Property>();
        List<Setting.Offset_Property> Diven_Offset = new List<Setting.Offset_Property>();
        private int Total_points;//当前组gamma的绑点数
        private double[,] D_lums;//目标值-单色
        private double[] D_lum;//目标值-白色
        private double auto_lum;  //  存放获取到的产品亮度值
        private double auto_x;
        private double auto_y;        //  存放获取到的产品亮度 色坐标 x,y
        private double R_x = 0.679;//
        private double R_y = 0.321;
        private double G_x = 0.239;
        private double G_y = 0.717;
        private double B_x = 0.138;
        private double B_y = 0.0479;
        private double D_x, D_y;
        double Lr_d, Lg_d, Lb_d;
        private int flag1 = 1;
        private int flag2 = 1;
        private int flag3 = 1;
        byte rstep = 16; byte gstep = 16; byte bstep = 16;
        bool STOPAutoGammaFlag = false;     //AutoGamma 停止标志位，解决定时器禁止后AutoGamma无法停止的问题
        uint GammaValueMax = 0x3FF - 1;//  需要修改
        private int index = 1;  //AutoGamma 调整顺序
        bool JumpGammaAdjustFlag = false;  //跳过某个绑点标志位，通常用于末尾低灰阶
        private double lum_off, x_off, y_off;
        bool ReceivOKFlag = false;
        UInt32 timeout = 0;
        private int[] Point_VTDR6110C_ZCQ = new int[25] { 0, 1, 3, 5, 7, 11, 15, 19, 23, 27, 31, 35, 39, 47, 55, 63, 71, 79, 95, 111, 127, 159, 191, 223, 255 };//绑点灰阶，从低到高 需要修改
        String[] Gamma_Band_Page = new string[50];
        byte GPN = 36; //保存Gamma绑点数量
        bool GammatuningOKFlag = false;
        private uint[,] GammaValue = new uint[36, 3];//保存当前Gammavalue
        bool lastdirupR = true; bool lastdirupG = true; bool lastdirupB = true; // Gamma 调整方向
        private byte[] Send_buf = new byte[1];
        int[] Receive_gamma_R = new int[27];
        int[] Receive_gamma_G = new int[27];
        int[] Receive_gamma_B = new int[27];
        bool load_pic_gamma = false;
        bool Autoloadgamma = false;
        private string[] gamma_r = new string[54]//需要修改
           {
                  "0x00","0x01","0x02","0x03","0x04","0x05","0x06","0x07","0x08","0x09","0x0A","0x0B","0x0C","0x0D","0x0E","0x0F","0x10","0x11",
            "0x12","0x13","0x14","0x15","0x16","0x17","0x18","0x19","0x1A","0x1B","0x1C","0x1D","0x1E","0x1F","0x20","0x21","0x22","0x23",
            "0x24","0x25","0x26","0x27","0x28","0x29","0x2A","0x2B","0x2D","0x2F","0x30","0x31","0x32","0x33","0x34","0x35","0x36","0x37"
           };
        private string[] gamma_g = new string[54]//需要修改
        {
                "0x38","0x39","0x3A","0x3B","0x3D","0x3F","0x40","0x41","0x42","0x43","0x44","0x45","0x46","0x47","0x48","0x49","0x4A","0x4B",
            "0x4C","0x4D","0x4E","0x4F","0x50","0x52","0x53","0x54","0x55","0x56","0x57","0x58","0x59","0x5A","0x5B","0x5C","0x5D","0x5E",
            "0x5F","0x60","0x61","0x62","0x63","0x64","0x65","0x66","0x67","0x68","0x69","0x6A","0x6B","0x6C","0x6D","0x6E","0x6F","0x70"
        };
        private string[] gamma_b = new string[54]//需要修改
        {
                "0x71","0x72","0x73","0x74","0x75","0x76","0x77","0x78","0x79","0x7A","0x7B","0x7C","0x7D","0x7E","0x7F","0x80","0x81","0x82",
            "0x83","0x84","0x85","0x86","0x87","0x88","0x89","0x8A","0x8B","0x8C","0x8D","0x8E","0x8F","0x90","0x91","0x92","0x93","0x94",
            "0x95","0x96","0x97","0x98","0x99","0x9A","0x9B","0x9C","0x9D","0x9E","0x9F","0xA0","0xA2","0xA3","0xA4","0xA5","0xA6","0xA7"
        };

        public VTDR6110C_ZCQ(frmMain Frm)
        {
            frmTop = Frm;
            InitializeComponent();
            frmTop.Child_window_hide_already = true;
            frmTop.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体  
        }

        private void VTDR6110C_ZCQ_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmTop.comPort.DataReceived -= new SerialDataReceivedEventHandler(VTDR6110C_ZCQ_DataReceived);
            frmTop.comPort.DataReceived += new SerialDataReceivedEventHandler(frmTop.SerialPort1_DataReceived);
            frmTop.textBox1.Text = frmTop.textBox1.Text + "VTDR6110C_ZCQ_Gamma_FormClosed！\r\n";
            frmTop.Child_Gamma_Window_Open_Enable = true; //允许其他子窗体打开
            frmTop.Child_window_hide_already = false;
            frmTop.IC_comboBox.Enabled = true;
            firstGammaFlag = true;
        }

        private void VTDR6110C_ZCQ_FormClosing(object sender, FormClosingEventArgs e)
        {

            e.Cancel = true;
            this.Hide();
        }

        private void tbx_load(string tbx_path, TextBox textBox) //输入一个txt的所在的路径和一个textbox的名字，将txt中的内容load到textbox中
        {
            if (File.Exists(tbx_path))
            {
                textBox.Clear();
                FileStream fs = new FileStream(tbx_path, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string str_generate = streamReader.ReadLine();
                //循环读取文本信息
                while (str_generate != null)
                {
                    if (str_generate.Contains("Gamma_ads_R:"))
                    {
                        Gamma_ads_R.Clear();
                        str_generate = str_generate.Replace("Gamma_ads_R:", "");
                        Gamma_ads_R.AppendText(str_generate);
                    }
                    else if (str_generate.Contains("Gamma_ads_G:"))
                    {
                        Gamma_ads_G.Clear();
                        str_generate = str_generate.Replace("Gamma_ads_G:", "");
                        Gamma_ads_G.AppendText(str_generate);
                    }
                    else if (str_generate.Contains("Gamma_ads_B:"))
                    {
                        Gamma_ads_B.Clear();
                        str_generate = str_generate.Replace("Gamma_ads_B:", "");
                        Gamma_ads_B.AppendText(str_generate);
                    }
                    else if (str_generate.Contains("Gamma_value_MAX:"))
                    {
                        str_generate = str_generate.Replace("Gamma_value_MAX:", "");
                        num_gammavaluemax.Value = Convert.ToInt32(str_generate);
                    }
                    else
                    {
                        textBox.AppendText(str_generate + "\r\n");
                    }
                    str_generate = streamReader.ReadLine(); //循环读取下一行
                }
                fs.Close(); //关闭流
                streamReader.Close();
                showmsg(tbx_path + "  载入完成");
            }
            else
            {
                showmsg(tbx_path + "不存在");
            }
        }
        private void VTDR6110C_ZCQ_Load(object sender, EventArgs e)//用于load一些需要保存的textbox中的内容
        {
            string defualtinfPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\2K_CFG\\Gamma_CFG";
            if (!Directory.Exists(defualtinfPath))
            {
                Directory.CreateDirectory(defualtinfPath);
                return;
            }
            defualtinfPath = defualtinfPath + "\\VTDR6110C_ZCQform" + ".txt";
            if (File.Exists(defualtinfPath))
            {
                FileStream fs = new FileStream(defualtinfPath, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("UTF-8"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string str_generate = streamReader.ReadLine();
                //循环读取文本信息
                while (str_generate != null)
                {
                    if (str_generate.Contains("Gamma_SetBox"))
                    {
                        str_generate = str_generate.Replace("Gamma_SetBox:", "");
                        tbx_load(str_generate, VTDR6110C_ZCQ_Gamma_SetBox);
                    }
                    str_generate = streamReader.ReadLine(); //循环读取下一行
                }
                fs.Close(); //关闭流
                streamReader.Close();

            }

        }
        private void VTDR6110C_ZCQ_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//Getting data from Comm Port
        {
            if (IClosing)
            { return; }
            try
            {
                Listening = true;//设置标记，说明我已经开始处理数据，一会儿要使用系统UI的。         
                int n = frmTop.comPort.BytesToRead;
                byte[] buf = new byte[n];
                Setting.TempRecord.cmdLen = n;
                frmTop.comPort.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到    
                buffer.AddRange(buf);
                byte CRCH, CRCL;
                if (buffer.Count > 3)
                {
                    //RECEIVE
                    // 0x0A: 模组Timing参数 设置  返回
                    // 0x0D: 模组的SSD2828配置数据、DriverIC初始化数据  设置  返回
                    // 0x2F: Demura操作    设置  返回
                    // 0x99: 通用读写、寄存器读写  设置  返回
                    // 0x9E: 功耗测试单元  设置  返回
                    if ((buffer[0] == 0x99) && (Setting.TempRecord.cmdLen > 0))
                    {

                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }
                    }
                    else if ((buffer[0] == 0x6B) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);
                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }

                    }
                    else if (((buffer[0] == 0x1D) || (buffer[0]) == 0x76 || (buffer[0] == 0x0D) || (buffer[0] == 0x0A) || (buffer[0] == 0x2F) || (buffer[0] == 0x99) || (buffer[0] == 0x9e) || (buffer[0] == 0x9f)) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }
                    }

                    else
                        buffer.RemoveRange(0, buffer.Count);
                }
                if (data_1_catched)
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        frmTop.T1.Enabled = false; //停止超时计数
                        if (Rec_tmp[0] == 0x6B) //
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        //  if (Rec_tmp[4] == 0x00)
                                        //     frmTop.textBox1.Text = frmTop.textBox1.Text + "DDIC 寄存器\t写 OK！\r\n";
                                        //txttip.Text = String.Format("{0:X2}", Rec_tmp[3]) + "寄存器写OK\r\n";
                                    }
                                    break;
                                case 0x02:
                                    {
                                        string tmp = "";                    //8bit  read
                                        //reText.Text = "";
                                        {
                                            for (int i = 0; i <= (Rec_tmp[4] + 1); i++)
                                            {
                                                if (i == (Rec_tmp[4] + 1))
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i + 3]);//16进制

                                                }
                                                else if (i == 1)
                                                {
                                                    //不显示回读位数
                                                }
                                                else
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i + 3]) + ",";//16进制
                                                }

                                            }
                                        }
                                        // frmTop.Generate_Read_Result_txt.AppendText(tmp + "\r\n");
                                        // reText.Text = tmp;
                                        Application.DoEvents();
                                    }
                                    break;
                                case 0x09:                 //read gamma
                                    {
                                        // if (Rec_tmp[4] == 0x00)
                                        frmTop.textBox1.Text = frmTop.textBox1.Text + "Gamma寄存器Read OK！\r\n";
                                        // frmTop.textBox1.Text = frmTop.textBox1.Text + BitConverter.ToString(Rec_tmp);
                                        int i = 5;
                                        //Array.Copy(Rec_tmp, 5, GammaValueReceived, 0, 150);
                                        for (i = 0; i < 25; i++)
                                        {
                                            //GammaValue[i, 0] = (uint)(Rec_tmp[i * 2 + 5] << 8) + Rec_tmp[i * 2 + 6];
                                            //GammaValue[i, 1] = (uint)(Rec_tmp[i * 2 + 5 + 50] << 8) + Rec_tmp[i * 2 + 6 + 50];
                                            //GammaValue[i, 2] = (uint)(Rec_tmp[i * 2 + 5 + 100] << 8) + Rec_tmp[i * 2 + 6 + 100];
                                        }

                                        for (i = 0; i < 25; i++)
                                        {
                                            //DataGirdShow((byte)i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                                        }
                                    }
                                    break;
                                case 0x0D:
                                    {
                                        //  if (Rec_tmp[4] == 0x00)
                                        //     frmTop.textBox1.Text = frmTop.textBox1.Text + "DDIC 寄存器\t写 OK！\r\n";
                                        //txttip.Text = "gamma OTP OK\r\n";
                                    }
                                    break;
                                default: break;

                            }
                        }
                        //--------------------------------------------Power Test---------------
                        else if (Rec_tmp[0] == 0x9E)  // PowerTest
                        {
                            switch (Rec_tmp[3])
                            {
                                case 0x00:
                                    {

                                    }
                                    break;
                                default:
                                    break;
                            }
                        }

                        //--------------------------------------------通用读写----------------------------------------------
                        else if (Rec_tmp[0] == 0x99) //GENWR
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        if (Rec_tmp[4] == 0x00) ;
                                        //txttip.Text = txttip.Text + "DDIC 寄存器\t写 OK！\r\n";
                                    }
                                    break;
                                case 0x02:
                                    {

                                    }
                                    break;
                                case 0x03:
                                    {
                                        string tmp = "";
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[3]) + ",";  //16进制
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[4]) + ",";//16进制
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[5]);      //16进制

                                        //txttip.Text += "DDIC 16bit寄存器--读 OK！\r\n";
                                        //txttip.AppendText(tmp + "\r\n");

                                        Application.DoEvents();

                                    }
                                    break;
                            }
                        }
                        //----------------------------------------------------------------------------------------------------                       
                        else if (Rec_tmp[0] == 0x9f)    //小黄窗的通用命令读写
                        {
                            //txttip.Text += "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "命令已执行" + "\r\n";
                            //txttip.SelectionStart = this.txttip.Text.Length;
                            //txttip.ScrollToCaret();//滚动到光标处
                            //if (txttip.Lines.Length > 50) txttip.Text = null;
                        }
                        else if (Rec_tmp[0] == 0x76)
                        {
                            if ((Rec_tmp[3] & 0x10) == 0x10)    //27p
                            {
                                if ((Rec_tmp[3] & 0x0f) == 0x01)
                                {
                                    for (int a = 0; a < 27; a++)
                                    {
                                        Receive_gamma_R[a] = Convert.ToInt32((Rec_tmp[5 + 2 * a] & 0x03)) * 256 + Convert.ToInt32(Rec_tmp[6 + 2 * a]);
                                    }
                                    frmTop.textBox1.Text = frmTop.textBox1.Text + "红 Gamma数据\t读 OK！\r\n";
                                }
                                else if ((Rec_tmp[3] & 0x0f) == 0x02)
                                {
                                    for (int a = 0; a < 27; a++)
                                    {
                                        Receive_gamma_G[a] = Convert.ToInt32((Rec_tmp[5 + 2 * a] & 0x03)) * 256 + Convert.ToInt32(Rec_tmp[6 + 2 * a]);
                                    }
                                    frmTop.textBox1.Text = frmTop.textBox1.Text + "绿 Gamma数据\t读 OK！\r\n";
                                }
                                else if ((Rec_tmp[3] & 0x0f) == 0x03)
                                {
                                    for (int a = 0; a < 27; a++)
                                    {
                                        Receive_gamma_B[a] = Convert.ToInt32((Rec_tmp[5 + 2 * a] & 0x03)) * 256 + Convert.ToInt32(Rec_tmp[6 + 2 * a]);
                                    }
                                    frmTop.textBox1.Text = frmTop.textBox1.Text + "蓝 Gamma数据\t读 OK！\r\n";
                                }

                            }
                            if (GammaReg_dataGridView.RowCount < 28)
                            {
                                for (int j = GammaReg_dataGridView.RowCount; j <= 27; j++)
                                {
                                    DataGridViewRow Row1 = new DataGridViewRow();
                                    GammaReg_dataGridView.Rows.Add(Row1);
                                }
                            }
                            for (int Ga_rows = 0; Ga_rows < 27; Ga_rows++)
                            {
                                GammaReg_dataGridView.Rows[Ga_rows].Cells[2].Value = Convert.ToInt32(Receive_gamma_R[Ga_rows]);
                                GammaReg_dataGridView.Rows[Ga_rows].Cells[3].Value = Convert.ToInt32(Receive_gamma_G[Ga_rows]);
                                GammaReg_dataGridView.Rows[Ga_rows].Cells[4].Value = Convert.ToInt32(Receive_gamma_B[Ga_rows]);
                            }
                        }
                    }));
                }
            }
            finally
            {
                Listening = false;
            }
        }

        private void VTDR6110C_ZCQ_VisibleChanged(object sender, EventArgs e)
        {
            if (frmTop.Child_window_hide_already == false) //子窗体已开启标识
            {
                ////frmTop.comPort.Close()
                frmTop.comPort.DataReceived -= new SerialDataReceivedEventHandler(VTDR6110C_ZCQ_DataReceived);
                frmTop.comPort.DataReceived += new SerialDataReceivedEventHandler(frmTop.SerialPort1_DataReceived);
                ////frmTop.comPort.Open();
                frmTop.textBox1.Text = frmTop.textBox1.Text + "VTDR6110C_ZCQ_Gamma_FormHide！\r\n";
                frmTop.Child_window_hide_already = true; //子窗体已隐藏标识
            }
            else
            {
                frmTop.comPort.DataReceived -= new SerialDataReceivedEventHandler(frmTop.SerialPort1_DataReceived);
                frmTop.comPort.DataReceived += new SerialDataReceivedEventHandler(VTDR6110C_ZCQ_DataReceived);
                frmTop.textBox1.Text = frmTop.textBox1.Text + "VTDR6110C_ZCQ_Gamma_FormOpened！\r\n";
                frmTop.Child_window_hide_already = false; //子窗体已开启标识
            }
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (VTDR6110C_ZCQ_Gamma_SetBox.Text == string.Empty)
            {
                MessageBox.Show("内容为空!");
                return;
            }
            //创建保存对话框对象
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "gamma cfg files (*.txt)|*.txt"; //过滤文件类型
            save.FilterIndex = 1;
            save.RestoreDirectory = true;
            if (save.ShowDialog() == DialogResult.OK)
            {
                string path = save.FileName;
                save.DefaultExt = ".txt";
                StreamWriter sw = new StreamWriter(path);
                sw.WriteLine(VTDR6110C_ZCQ_Gamma_SetBox.Text);
                sw.Close();
            }

            string defualtinfPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\2K_CFG\\Gamma_CFG";
            if (!Directory.Exists(defualtinfPath))
            {
                Directory.CreateDirectory(defualtinfPath);
            }
            defualtinfPath = defualtinfPath + "\\VTDR6110C_ZCQform" + ".txt";
            StreamWriter ssw = new StreamWriter(defualtinfPath);
            ssw.WriteLine("Gamma_SetBox:" + save.FileName);
            ssw.Close();
            showmsg("gamma脚本保存完成");

        }

        private void 载入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "精度配置文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "gamma cfg write";

            if (of.ShowDialog() == DialogResult.OK)
            {
                tbx_load(of.FileName, VTDR6110C_ZCQ_Gamma_SetBox);

                string defualtinfPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\2K_CFG\\Gamma_CFG";
                if (!Directory.Exists(defualtinfPath))
                {
                    Directory.CreateDirectory(defualtinfPath);
                }
                defualtinfPath = defualtinfPath + "\\VTDR6110C_ZCQform" + ".txt";
                StreamWriter ssw = new StreamWriter(defualtinfPath);
                ssw.WriteLine("Gamma_SetBox:" + of.FileName);
                ssw.Close();
            }
        }

        private void numStep_ValueChanged(object sender, EventArgs e)   //手动调整AutoGamma调节步长以在初次调整Gamma是提升速度
        {
            rstep = (byte)(int.Parse(numStep.Value.ToString()));
            gstep = (byte)(int.Parse(numStep.Value.ToString()));
            bstep = (byte)(int.Parse(numStep.Value.ToString()));
        }

        private void btn_flexible_gamma_Click(object sender, EventArgs e)
        {
            Multi_gamma_txt_now_index = 0;
            Multi_gamma_txt_line_count = this.VTDR6110C_ZCQ_Gamma_SetBox.Lines.GetUpperBound(0);
            Multi_flexible_gammas(Multi_gamma_txt_now_index, out Multi_gamma_txt_next_index);
        }

        private void VTDR6110C_ZCQ_RegWR_Click(string w_reg)
        {
            string[] w_reg_1 = w_reg.Split(',');
            byte[] TepArr;
            try
            {
                TepArr = new byte[w_reg_1.Length + 1];
                TepArr[0] = Convert.ToByte(w_reg_1.Length);
                for (int i = 1; i < TepArr.Length; i++)
                {
                    TepArr[i] = (byte)Convert.ToInt32(w_reg_1[i - 1], 16);
                }
                frmMain.frmain.comPort.Write(GetCRCArray_9f(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾
                //frmMain.frmain.comPort.Write(GetCRCArray_99(gamma_page, 1), 0, gamma_page.Length + 4);//循环部分，每段数据结尾
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
        }
        private void Multi_flexible_gammas(int txt_index, out int list_view_index)
        {
            index = 1;  //Gamma绑点序号，第一个绑点通常对应255灰阶
            JumpGammaAdjustFlag = false;
            frmMain.frmain.textBox1.ForeColor = Color.Black;
            STOPAutoGammaFlag = false;
            flag1 = flag2 = flag3 = 1;
            int flag = 1;
            frmTop.cbxlogic_go.Checked = false;//逻辑图开关默认关

            string strLine = Convert.ToString(VTDR6110C_ZCQ_Gamma_SetBox.Text);
            string[] arr = strLine.Split(','); //以逗号分割，添加到数组
            string perline = string.Empty;

            list_view_index = 0;

            if (frmMain.frmain.btnCal_manual.Tag.ToString() != "0calDone")
            {
                frmMain.frmain.btnCal_manual.Enabled = true;
                MessageBox.Show("需要提前连接410并校准~", "提示：");
                return;
            }

            if (VTDR6110C_ZCQ_Gamma_SetBox.Text == string.Empty)
            {
                MessageBox.Show("内容为空!");
                return;
            }
            else  //标记关键事件
            {
                try
                {
                    arr = strLine.Split('\n'); //以逗号分割，添加到数
                    for (int i = txt_index; i < arr.Length;)  //获取的行数
                    {
                        perline = arr[i];
                        perline = perline.Replace(" ", "");
                        perline = perline.Replace(";", "");
                        perline = perline.Replace("(", "");
                        perline = perline.Replace(")", "");
                        perline = perline.Replace("\r", "");
                        perline = perline.Replace("\n", "");

                        if (perline.Contains("//"))
                        {
                            int zhushi = perline.IndexOf("//");
                            if (zhushi == 0)
                            {
                                i = i + 1;
                                continue;
                            }
                            perline = perline.Substring(0, zhushi);
                        }

                        if (perline.Contains("REGW"))
                        {
                            perline = perline.Replace("REGW", "");
                            VTDR6110C_ZCQ_RegWR_Click(perline);
                            Thread.Sleep(50);
                            i = i + 1;
                        }

                        else if (perline.Contains("SAVE"))
                        {
                            btnSaveGamma_Click(btnSaveGamma, null);
                            Thread.Sleep(50);
                            showmsg("Gamma " + GammaBandSelect.Text + "保存完成");
                            i = i + 1;
                        }
                        else if (perline.Contains("GAMMA_PAGE"))
                        {
                            perline = perline.Replace("GAMMA_PAGE", "");
                            perline = perline.Replace("_", "");
                            GammaPageSelect.Text = perline;
                            VTDR6110C_ZCQ_RegWR_Click(perline);
                            Thread.Sleep(50);
                            i = i + 1;
                        }
                        else if (perline.Contains("LOGIC_GAMMA"))//指向主界面logic图调gamma
                        {
                            frmTop.cbxlogic_go.Checked = true;
                            perline = perline.Replace("LOGIC_GAMMA", "");
                            perline = perline.Replace("_", "");
                            String[] perline_A = perline.Split(',');
                            for (int logi = 0; logi < perline_A.Length; logi++)
                            {
                                perline_A[logi] = perline_A[logi].Replace(":", "");
                                if (perline_A[logi].Contains("图形样式"))
                                {
                                    perline_A[logi] = perline_A[logi].Replace("图形样式", "");
                                    switch (perline_A[logi])
                                    {
                                        case "0":
                                            {
                                                frmTop.CBX_HFZ_LOGIC.SelectedIndex = 0;
                                            }
                                            break;
                                        case "1":
                                            {
                                                frmTop.CBX_HFZ_LOGIC.SelectedIndex = 1;
                                            }
                                            break;
                                        case "2":
                                            {
                                                frmTop.CBX_HFZ_LOGIC.SelectedIndex = 2;
                                            }
                                            break;
                                        case "3":
                                            {
                                                frmTop.CBX_HFZ_LOGIC.SelectedIndex = 3;
                                            }
                                            break;
                                        case "4":
                                            {
                                                frmTop.CBX_HFZ_LOGIC.SelectedIndex = 4;
                                            }
                                            break;
                                        default: break;
                                    }
                                }
                                if (perline_A[logi].Contains("X0"))
                                {
                                    perline_A[logi] = perline_A[logi].Replace("X0", "");
                                    frmTop.HFZ_X0.Value = Convert.ToInt32(perline_A[logi]);
                                }
                                if (perline_A[logi].Contains("X1"))
                                {
                                    perline_A[logi] = perline_A[logi].Replace("X1", "");
                                    frmTop.HFZ_X1.Value = Convert.ToInt32(perline_A[logi]);
                                }
                                if (perline_A[logi].Contains("Y0"))
                                {
                                    perline_A[logi] = perline_A[logi].Replace("Y0", "");
                                    frmTop.HFZ_Y0.Value = Convert.ToInt32(perline_A[logi]);
                                }
                                if (perline_A[logi].Contains("Y1"))
                                {
                                    perline_A[logi] = perline_A[logi].Replace("Y0", "");
                                    frmTop.HFZ_Y1.Value = Convert.ToInt32(perline_A[logi]);
                                }
                                if (perline_A[logi].Contains("R"))
                                {
                                    perline_A[logi] = perline_A[logi].Replace("R", "");
                                    frmTop.HFZ_R.Value = Convert.ToInt32(perline_A[logi]);
                                }
                            }
                            Thread.Sleep(50);
                            i = i + 1;
                        }
                        else if (perline.Contains("LOAD_BMP_GAMMA"))//用于load bmp图调gamma，指令格式：__LOAD_BMP_GAMMA(路径)；路径是文件夹路径，图片命名方式是：_255_.bmp 中间255是灰阶
                        {
                            perline = perline.Replace("LOAD_BMP_GAMMA", "");
                            perline = perline.Replace("_", "");
                            GammaPageSelect.Text = perline;
                            if (!Directory.Exists(perline))
                            {
                                MessageBox.Show("文件夹不存在");
                                return;
                            }
                            DirectoryInfo di = new DirectoryInfo(perline);
                            frmTop.listBox3_BMPFile.Items.Clear();
                            frmTop.CreateListItem(di);//递归加载文件夹里的所有图片
                                                      // textBox2.Text = path;
                                                      // -------------------------------------------------------------------------
                            StreamWriter sw = null; //文件流
                            sw = new StreamWriter("./update/Picaddr.txt", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
                            sw.Write(frmTop.defaultfilePath);
                            sw.Dispose(); //释放资源
                            sw.Close(); //关闭数据流
                            Thread.Sleep(50);
                            load_pic_gamma = true;
                            i = i + 1;
                        }
                        else if (perline.Contains("GAMMA_SET"))
                        {
                            perline = perline.Replace("GAMMA_SET", "");
                            perline = perline.Replace("_", "");
                            System.Diagnostics.Debug.Print(Multi_gamma_group_index.ToString());             // 华丽的分割线----------------------
                            GammaBandSelect.Text = perline;
                            try
                            {
                                btnSaveGamma_Click(btnLoadGamma, null);
                                VTDR6110C_ZCQ_Gamma_write_Click(null, null);
                                showmsg("自动loadgamma完成");
                                Application.DoEvents();
                            }
                            catch {; }

                            ArrayList list = new ArrayList();
                            do
                            {
                                i = i + 1;
                                perline = arr[i];
                                list.Add(perline + "\n");
                            } while (perline.Contains("GAMMA_TUNING") == false);
                            string[] gamma_set_lines = (string[])list.ToArray(typeof(string));
                            for (int j = 0; j < gamma_set_lines.Length; j++)                        // 华丽的分割线----------------------
                            {
                                System.Diagnostics.Debug.Print(gamma_set_lines[j]);             // 华丽的分割线----------------------
                            }

                            Text_Processing(gamma_set_lines);
                            GPN = (byte)Point_VTDR6110C_ZCQ.Length; // 获取Gamma绑点数量
                            switch (flag)
                            {
                                case 1://寄存器值与亮度正比
                                    {
                                        //lum_off = Convert.ToDouble(txtVT_loff.Text);
                                        x_off = Convert.ToDouble(txtVT_xoff.Text);   //获取色坐标允差范围
                                        y_off = Convert.ToDouble(txtVT_yoff.Text);

                                        if (load_pic_gamma == true)
                                        {
                                            for (int pic_i = 0; pic_i < frmTop.listBox3_BMPFile.Items.Count; pic_i++)
                                            {
                                                if (frmTop.listBox3_BMPFile.Items[pic_i].ToString().Contains("_" + Point_VTDR6110C_ZCQ[GPN - index].ToString() + "_.bmp"))
                                                {
                                                    frmTop.listBox3_BMPFile.SelectedIndex = pic_i;
                                                    frmTop.btnPrevPic_Click(null, null);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            frmMain.frmain.numPatternR.Value = Point_VTDR6110C_ZCQ[GPN - index];     //设定绑点灰阶
                                                                                                                     //numPatternG.Value = Point_RM692G3[GPN - index];
                                                                                                                     //numPatternB.Value = Point_RM692G3[GPN - index];
                                            frmMain.frmain.OLED_Show_Click(frmMain.frmain.btnPatternW, null);       //显示255白画面，从255白画面开始调节
                                        }
                                        Band_index.Text = "绑点:" + Point_VTDR6110C_ZCQ[GPN - index].ToString();
                                        Msr_CA310();
                                        Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题
                                        ReceivOKFlag = false;
                                        timeout = 0;
                                    }
                                    break;
                                case 2:  //寄存器值与亮度反比
                                    break;
                                default:
                                    break;
                            }
                            list_view_index = i;
                            Application.DoEvents();
                            GammaTuning();
                            Application.DoEvents();
                            break;
                        }
                        else
                        {
                            i = i + 1;
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("输入格式有误！");
                }

            }
        }

        public void DataGirdShow(byte index, double RRR, double GGG, double BBB)        //UI 表格显示 R/G/B对应Gamma寄存器值
        {
            int Row_Accum = 0, Current_Index = 0, Row_flag = 0;

            DataGridViewRow Row1 = new DataGridViewRow();

            Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
            if (Row_Accum != 0)
            {
                Current_Index = this.GammaReg_dataGridView.SelectedCells[0].RowIndex;
                if ((Current_Index != Row_Accum - 1) && (Current_Index != Row_Accum))
                {
                    Row_Accum = Current_Index;
                    Row_flag = 1;
                }
                else
                {
                    this.GammaReg_dataGridView.Rows.Add(Row1);
                }
                if ((Row_Accum != 0) && (Row_flag != 1))
                {
                    if (Current_Index != Row_Accum)
                    {
                        this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = false;
                        this.GammaReg_dataGridView.Rows[Row_Accum].Selected = true;
                    }
                }
            }
            else
            {
                this.GammaReg_dataGridView.Rows.Add(Row1);
            }
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[0].Value = index + 1;//序号
            //Rows[x]为第x行,Cells[x]为第x列
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[1].Value = (D_lum[index]).ToString("#0.0000");
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[2].Value = RRR;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[3].Value = GGG;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[4].Value = BBB;

            if (Row_flag == 1)
            {
                Row_flag = 0;
                Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
                this.GammaReg_dataGridView.Rows[Current_Index].Selected = false;
                this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = true;
            }
            GammaReg_dataGridView.FirstDisplayedScrollingRowIndex = GammaReg_dataGridView.RowCount - 1;
        }

        private void CheckandCorrectGammaValue()   //检查GammaValue 是否按照大小排列
        {
            bool Gamma_value_def = false;
            uint GammaValueMax = (uint)num_gammavaluemax.Value - 1;
            byte i; GPN = (byte)Point_VTDR6110C_ZCQ.Length; // 获取Gamma绑点数量
            GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] & GammaValueMax + 1;
            GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] & GammaValueMax + 1;
            GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] & GammaValueMax + 1;
            if (GammaValue[GPN - 1, 0] > GammaValueMax)
            {
                GammaValue[GPN - 1, 0] = GammaValueMax - 16;
            }
            if (GammaValue[GPN - 1, 1] > GammaValueMax)
            {
                GammaValue[GPN - 1, 1] = GammaValueMax - 16;
            }
            if (GammaValue[GPN - 1, 2] > GammaValueMax)
            {
                GammaValue[GPN - 1, 2] = GammaValueMax - 16;
            }  //确保GammaValue不要超过DDIC 中Gamma寄存能接受的最大值

            for (i = (byte)(GPN - index); i > 0; i--)    //低灰阶GammaValue如果大于高灰阶GammaValue则强制变小
            {
                if (GammaValue[i, 0] < GammaValue[i - 1, 0])
                {
                    GammaValue[i - 1, 0] = GammaValue[i, 0] - 0;
                    Gamma_value_def = true;
                }
                if (GammaValue[i, 1] < GammaValue[i - 1, 1])
                {
                    GammaValue[i - 1, 1] = GammaValue[i, 1] - 0;
                    Gamma_value_def = true;
                }
                if (GammaValue[i, 2] < GammaValue[i - 1, 2])
                {
                    GammaValue[i - 1, 2] = GammaValue[i, 2] - 0;
                    Gamma_value_def = true;
                }
            }
            if (Gamma_value_def)
            {
                //GammaValueSet(1);//如果存在低灰阶绑点value值大于高灰阶，那么更新低灰阶值，并写入ic
            }
            GammaValue[0, 0] = 0; GammaValue[0, 1] = 0; GammaValue[0, 2] = 0;

            if (chkGammaGridViewFresh.Checked)   // 刷新UI界面GammaValue值显示
            {
                this.GammaReg_dataGridView.Rows.Clear();
                for (i = 0; i < GPN; i++)
                {
                    DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                }
            }
        }

        private void GammavalueCal(int index)
        {// GammaValue = new uint[36, 3];//保存当前Gammavalue
            GammaValue[0, 1] = 0;
            //double[] x = new double[] { 610, 748, 865, 965, 1049, 1127, 1199, 1266, 1381, 1547, 1675, 1785, 1967, 2007 };
            //double[] y = new double[] { 675, 844 ,977, 1087, 1176, 1251, 1316, 1373, 1472, 1632, 1763, 1877, 2066, 2109 };
            double[] x = new double[16];
            double[] y = new double[16];

            //double[] y = new double[] { 675, 844, 977, 1087, 1176, 1251, 1316, 1373, 1472, 1632, 1763, 1877, 2066, 2109 };
            //double[] res = MathNet.Numerics.Fit.Polynomial(x, y, 2);
            //double r = Correlation.Pearson(x, y);//             
            //for (byte i=0;i<13;i++)
            //{
            //    double yy = res[0] + res[1] * x[i] + res[2] * (Math.Pow(x[i], 2.0));
            //}
            ////----------------------
            //double[] x1 = new double[] { 1785, 1967, 2007 };
            //double[] y1 = new double[] {  1877,2066, 2109 };
            //double[] res1 = MathNet.Numerics.Fit.Polynomial(x1, y1, 2);
            //double r1 = Correlation.Pearson(x1, y1);// 

            //for (byte i = 0; i < 2; i++)
            //{
            //    double tep = 1675;                
            //    double yy1 = res[0] + res[1] * tep + res[2] * (Math.Pow(tep, 2.0));

            //}

        }

        private void showmsg(string str, params byte[] mesgshowLevel)
        {
            byte MsgshowLevel;
            if (mesgshowLevel != null && mesgshowLevel.Length > 0)
            {
                MsgshowLevel = mesgshowLevel[0];
            }
            else { MsgshowLevel = 0; }
            {
                txttip.Text += str + "\r\n";
                txttip.SelectionStart = txttip.Text.Length;
                txttip.ScrollToCaret();//滚动到光标处
                if (txttip.Lines.Length > 3800) txttip.Clear();
            }
        }

        static byte[] GetCRCArray_9f(byte[] arr, Byte speedflag)   //处理命令数组，在其头尾增加包头(9F,在一个包内包含多行code)以及CRC校验值，处理后的数据可以直接发送至下位机
        {
            CRC16 CRCData = new CRC16();//根据黑窗（99）黄窗（9f）手动测试写gamma结果，选择适当的gammacode打包下发方式  需要修改

            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 6;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x9f;//格式：9f,speedflag(高低速),有效数据长度+1,一行code长度，一行code内容（多个Byte），一行code长度，一行code内容。。。，0xFF(结束标志位),crc1,crc2。
            Send_Datax[1] = (byte)(speedflag << 4);
            Send_Datax[2] = Convert.ToByte(arr.Length + 1);  //为兼容下位机命令，此位置填待传输有效数据长度+1 

            Send_Datax[arr.Length + 3] = 0xFF;  //添加结束标志位
            arr.CopyTo(Send_Datax, 3);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }

        static byte[] GetCRCArray_99(byte[] arr, Byte speedflag)   //处理命令数组，在其头尾增加包头(9F,在一个包内包含多行code)以及CRC校验值，处理后的数据可以直接发送至下位机
        {
            CRC16 CRCData = new CRC16();

            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 4;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x99;
            Send_Datax[1] = 0x1f;//f指向mipi写入方式，8 9 A B C D E F分别指向了黑窗左边的8种写入方式，具体可参考黑窗的代码
            arr.CopyTo(Send_Datax, 2);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }

        private void VTDR6110C_ZCQ_Gamma_write_Click(object sender, EventArgs e)
        {
            VTDR6110C_ZCQ_RegWR_Click(GammaPageSelect.Text);
            btnGammaValueUpdate_Click(null, null);
            CheckandCorrectGammaValue();   //检查Gamma 是否存在高低灰阶数值错乱 ,并刷新表格数据              
            GammaValueSet(1); //GammaValue 转换成特定格式后再通过此函数写入DDIC
        }

        private void GammaValueSet(byte index)  //GammaValue从低绑点到高绑点     index从1开始至GPN   需要修改
        {
            byte[] TepArr;
            try
            {
                TepArr = new byte[] { 3, 0xf0, 0xaa, 0x13,
                    4, 0XFF, 0XFF, 0XFF, 25,//没有延时会偶发性gamma不生效
                    2, 0xbf, Convert.ToByte(GammaBandSelect.Text,16),   //gamma band
                    4, 0XFF, 0XFF, 0XFF, 25,
                    2, 0xc4, 0x01,
                    4, 0XFF, 0XFF, 0XFF, 25 };  //byte[] TepArr;

                frmMain.frmain.comPort.Write(GetCRCArray_9f(TepArr, 4), 0, TepArr.Length + 6);
                //-----------------  
                TepArr = new byte[] {
                17,0xB0, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xB1, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xB2, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                3, 0xB3, 00, 00,
                17,0xB4, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xB5, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xB6, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                3, 0xB7, 03, 00,
                17,0xB8, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xB9, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xBa, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                3, 0xBb, 00, 00,
                2,0xc4, 0x00
                };
                for (int i = 0; i < 25; i++)
                {
                    if (i < 8)//b0\b4\b8
                    {
                        TepArr[i * 2 + 2] = (byte)(((int)(GammaValue[i, 0]) >> 8) & 0x03);//gamma red   *2是两个byte表示一个绑点     +2是开头两个固定值未参与循环（17，0xb0）
                        TepArr[i * 2 + 2 + 1] = (byte)(((int)(GammaValue[i, 0])) & 0xff);//+1是指低位在前，高位在后，所以+1

                        TepArr[i * 2 + 2 + 54 + 4] = (byte)(((int)(GammaValue[i, 1]) >> 8) & 0x03);//gamma green   54=18*3,4=最后一个寄存器的数据长度（例如B3）
                        TepArr[i * 2 + 2 + 1 + 54 + 4] = (byte)(((int)(GammaValue[i, 1])) & 0xff);

                        TepArr[i * 2 + 2 + 54 + 4 + 54 + 4] = (byte)(((int)(GammaValue[i, 2]) >> 8) & 0x03);//gamma blue  
                        TepArr[i * 2 + 2 + 1 + 54 + 4 + 54 + 4] = (byte)(((int)(GammaValue[i, 2])) & 0xff);

                    }
                    else if (i > 7 && i < 16)
                    {
                        TepArr[i * 2 + 2 + 2] = (byte)(((int)(GammaValue[i, 0]) >> 8) & 0x03);//gamma red  循环到B1，多了一个17,0xB1，所以再+2
                        TepArr[i * 2 + 2 + 1 + 2] = (byte)(((int)(GammaValue[i, 0])) & 0xff);

                        TepArr[i * 2 + 2 + 54 + 4 + 2] = (byte)(((int)(GammaValue[i, 1]) >> 8) & 0x03);//gamma green
                        TepArr[i * 2 + 2 + 1 + 54 + 4 + 2] = (byte)(((int)(GammaValue[i, 1])) & 0xff);

                        TepArr[i * 2 + 2 + 54 + 4 + 54 + 4 + 2] = (byte)(((int)(GammaValue[i, 2]) >> 8) & 0x03);//gamma blue
                        TepArr[i * 2 + 2 + 1 + 54 + 4 + 54 + 4 + 2] = (byte)(((int)(GammaValue[i, 2])) & 0xff);
                    }
                    else if (i < 24 && i > 15)
                    {
                        TepArr[i * 2 + 2 + 2 + 2] = (byte)(((int)(GammaValue[i, 0]) >> 8) & 0x03);//gamma red
                        TepArr[i * 2 + 2 + 1 + 2 + 2] = (byte)(((int)(GammaValue[i, 0])) & 0xff);

                        TepArr[i * 2 + 60 + 4] = (byte)(((int)(GammaValue[i, 1]) >> 8) & 0x03);//gamma green
                        TepArr[i * 2 + 2 + 1 + 54 + 4 + 2 + 2] = (byte)(((int)(GammaValue[i, 1])) & 0xff);

                        TepArr[i * 2 + 2 + 54 + 4 + 54 + 4 + 2 + 2] = (byte)(((int)(GammaValue[i, 2]) >> 8) & 0x03);//gamma blue
                        TepArr[i * 2 + 2 + 1 + 54 + 4 + 54 + 4 + 2 + 2] = (byte)(((int)(GammaValue[i, 2])) & 0xff);
                    }
                    else//最后一个绑点25
                    {
                        TepArr[56] = (byte)(((int)(GammaValue[i, 0]) >> 8) & 0x03);//gamma red
                        TepArr[57] = (byte)(((int)(GammaValue[i, 0])) & 0xff);

                        TepArr[114] = (byte)(((int)(GammaValue[i, 1]) >> 8) & 0x03);//gamma green
                        TepArr[115] = (byte)(((int)(GammaValue[i, 1])) & 0xff);

                        TepArr[172] = (byte)(((int)(GammaValue[i, 2]) >> 8) & 0x03);//gamma blue
                        TepArr[173] = (byte)(((int)(GammaValue[i, 2])) & 0xff);
                    }
                }
                frmMain.frmain.comPort.Write(GetCRCArray_9f(TepArr, 4), 0, TepArr.Length + 6);//使用直接用9f的方式发gamma
                //string txtcmd3 = frmMain.frmain.Generate_textBox.Text;//利用主界面黑窗写gamma,下面的循环是将本来准备好的数组再解析为textbox中的格式，循环是固定格式
                //frmMain.frmain.Generate_textBox.Text = null;
                //for (int i = 0; i < TepArr.Length;)
                //{
                //    for (int j = 1; j < TepArr[i] + 1; j++)
                //    {
                //        if (j == TepArr[i])
                //        {
                //            frmMain.frmain.Generate_textBox.Text = frmMain.frmain.Generate_textBox.Text + Convert.ToString(TepArr[j + i], 16) + "\r\n";
                //        }
                //        else
                //        {
                //            frmMain.frmain.Generate_textBox.Text = frmMain.frmain.Generate_textBox.Text + Convert.ToString(TepArr[j + i], 16) + ",";
                //        }
                //    }
                //    i = i + TepArr[i] + 1;
                //}
                //frmMain.frmain.Generate_File_Click(frmMain.frmain.Generate_File_Run, null);



            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
        }

        private void GammaTuning()   //AutoGamma处理过程
        {
            double Lr_t, Lg_t, Lb_t, lumr, lumg, lumb;
            while (index <= GPN)
            {
                labTargetlum.Text = "Tar:" + D_lum[GPN - index].ToString("#0.0000");  // 在UI上显示当前绑点的目标亮度值
                txtVT_lum.Text = D_lum[GPN - index].ToString("#0.0000");//当前绑点目标亮度
                numVT_loff.Text = (Diven_Offset[index - 1].LUM_OFF * 100).ToString();//亮度误差百分比


                Thread.Sleep(20);
                Msr_CA310();
                lablvshow.Text = "Lv: " + auto_lum.ToString("f4").Substring(0, 6) + "\r\n" + "x: " + auto_x.ToString("f4") + "\r\n" + "y: " + auto_y.ToString("f4") + "\r\n";

                //showmsg("Adjust inex:" + GPN + "----" + index + "");
                lum_off = (D_lum[GPN - index] * Convert.ToDouble(numVT_loff.Text)) / 100;  //计算当前绑点允许的亮度误差范围
                x_off = Convert.ToDouble(Diven_Offset[index - 1].X_OFF);
                y_off = Convert.ToDouble(Diven_Offset[index - 1].Y_OFF);       //获取色坐标允许误差范围

                txtVT_xoff.Text = x_off.ToString();//更新每个绑点的目标亮度、亮度、色度误差
                txtVT_yoff.Text = y_off.ToString();
                if (auto_x < 0)
                { auto_x = 0; showmsg("TMD410数据又出错了"); }
                if (auto_y < 0)
                { auto_y = 0; showmsg("TMD410数据又出错了"); }

                if ((auto_lum < (D_lum[GPN - index] + lum_off)) && (auto_lum > (D_lum[GPN - index] - lum_off)))//
                    flag1 = 0;  //判断亮度以及色坐标是否在目标范围
                else flag1 = 1;
                if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                    flag2 = 0;  //判断亮度以及色坐标是否在目标范围
                else flag2 = 1;
                if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                    flag3 = 0;  //判断亮度以及色坐标是否在目标范围
                else flag3 = 1;
                if ((flag1 == 0 && flag2 == 0 && flag3 == 0) && (index < 12)) //低灰阶本来就很难调就不这么折腾了
                {   //初次判断调整OK后，再来复测一次，以消除偶发调不准问题
                    Thread.Sleep(10); Msr_CA310(); Thread.Sleep(10); Msr_CA310();
                    Msr_CA310();
                    if ((auto_lum < (D_lum[GPN - index] + lum_off)) && (auto_lum > (D_lum[GPN - index] - lum_off)))//
                        flag1 = 0;  //判断亮度以及色坐标是否在目标范围
                    else flag1 = 1;
                    if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                        flag2 = 0;  //判断亮度以及色坐标是否在目标范围
                    else flag2 = 1;
                    if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                        flag3 = 0;  //判断亮度以及色坐标是否在目标范围
                    else flag3 = 1;
                }//初次判断调整OK后，再来复测一次，以消除偶发调不准问题
                Lr_t = R_y * ((auto_y - G_y) * (B_x - auto_x) + (auto_x - G_x) * (auto_y - B_y)) / B_y / ((auto_y - G_y) * (auto_x - R_x) + (auto_x - G_x) * (R_y - auto_y));
                Lb_t = 1.0;
                Lg_t = G_y * ((auto_y - R_y) * (B_x - auto_x) + (auto_x - R_x) * (auto_y - B_y)) / B_y / ((auto_y - R_y) * (auto_x - G_x) + (auto_x - R_x) * (G_y - auto_y));
                lumr = auto_lum * Lr_t / (Lr_t + Lg_t + Lb_t);
                lumg = auto_lum * Lg_t / (Lr_t + Lg_t + Lb_t);
                lumb = auto_lum * Lb_t / (Lr_t + Lg_t + Lb_t);
                if ((lumr < 0))
                {
                    //lumr = 0;
                }
                if ((lumg < 0))
                {
                    //lumg = 0;
                }
                if ((lumb < 0))
                {
                    // lumb = 0;
                }
                if (((flag1 == 0 && flag2 == 0 && flag3 == 0) || JumpGammaAdjustFlag) || (timeout > 3 * numTurnGammaTimeout.Value))
                {
                    if (timeout > 3 * numTurnGammaTimeout.Value)
                    {
                        showmsg("\r\n....----模糊处理---模糊处理----....");
                    }
                    timeout = 0;
                    showmsg("Gamma" + GammaBandSelect.Text + ";绑点W" + Point_VTDR6110C_ZCQ[GPN - index].ToString());
                    showmsg("亮度" + auto_lum.ToString("F4"));
                    showmsg("X坐标" + auto_x.ToString("F4"));
                    showmsg("Y坐标" + auto_y.ToString("F4"));

                    showmsg("绑点No" + (GPN - index + 1) + "完成...\r\n");
                    index++;
                    if (index == GPN)   //  最后一个绑点通常为0，不用调试结束即可
                    {
                        //TimTest.Stop();//停止计时
                        GammatuningOKFlag = true;
                        showmsg("Gamma" + GammaBandSelect.Text + " 调试完成");
                        STOPAutoGammaFlag = true;
                        btn_VTDR6110C_ZCQ_Stop.PerformClick();

                        this.GammaReg_dataGridView.Rows.Clear();
                        for (byte i = 0; i < GPN; i++)
                        {
                            DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                        }

                        if (Multi_gamma_txt_next_index < Multi_gamma_txt_line_count)
                        {
                            Multi_gamma_txt_now_index = Multi_gamma_txt_next_index;
                            Multi_flexible_gammas(Multi_gamma_txt_now_index, out Multi_gamma_txt_next_index);
                        }
                        return;
                    }
                    if (index < GPN)
                    {
                        //showmsg("绑点" + index + "完成...\r\n");
                        for (int i = 0; i < 25; i++)    //本意用于显示当前绑点目标信息，但一般用不到
                        {
                            //Convert.ToString(要转的数, 16);//string s = string.Format("0x{0:X2}", i);    // s = 0x0F;
                            //Points_LV.Text += (i + 1) + ",R/G/B, V" + Point_Hi3288[24 - i] + ": " + string.Format("0x{0:X2}", GammaValue[24 - i, 0]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 1]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 2]) + "\r\n";

                            //this.GammaReg_dataGridView.Rows.Clear();
                            //DataGirdShow((byte)i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                            //Points_LV.Text += (i + 1) + ",R/G/B, V" + Point_Hi3288[24 - i] + ": " + string.Format("0x{0:X2}", GammaValue[24 - i, 0]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 1]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 2]) + "\r\n";
                        }
                        flag1 = 1;  //复位 亮度色坐标符合目标标志位
                        flag2 = 1;
                        flag3 = 1;
                        JumpGammaAdjustFlag = false;
                    }
                    rstep = (byte)(int.Parse(numStep.Value.ToString())); ;    //重新获取调节步长
                    gstep = (byte)(int.Parse(numStep.Value.ToString())); ;
                    bstep = (byte)(int.Parse(numStep.Value.ToString())); ;
                    if (load_pic_gamma == true)
                    {
                        for (int pic_i = 0; pic_i < frmTop.listBox3_BMPFile.Items.Count; pic_i++)
                        {
                            if (frmTop.listBox3_BMPFile.Items[pic_i].ToString().Contains("_" + Point_VTDR6110C_ZCQ[GPN - index].ToString() + "_.bmp"))
                            {
                                frmTop.listBox3_BMPFile.SelectedIndex = pic_i;
                                frmTop.btnPrevPic_Click(null, null);
                            }
                        }
                    }
                    else
                    {
                        frmMain.frmain.numPatternR.Value = Point_VTDR6110C_ZCQ[GPN - index];     //设定绑点灰阶
                                                                                                 //numPatternG.Value = Point_RM692G3[GPN - index];
                                                                                                 //numPatternB.Value = Point_RM692G3[GPN - index];
                        frmMain.frmain.OLED_Show_Click(frmMain.frmain.btnPatternW, null);       //显示255白画面，从255白画面开始调节
                    }
                    Band_index.Text = "绑点:" + Point_VTDR6110C_ZCQ[GPN - index].ToString();
                    //ReceivOKFlag = false;
                    Thread.Sleep(10);
                    Msr_CA310(); Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题
                    //--------------------------
                    GammavalueCal(index);
                    //--------------------------
                    if (!STOPAutoGammaFlag)
                        //T17.Enabled = true
                        ;
                }
                else
                {
                    if (timeout > numTurnGammaTimeout.Value)
                    {
                        //frmMain.frmain.numPatternR.Value = Point_RM692G3[GPN - index];     //设定绑点灰阶
                        //                                                                   //numPatternG.Value = Point_RM692G3[GPN - index];
                        //                                                                   //numPatternB.Value = Point_RM692G3[GPN - index];
                        //frmMain.frmain.OLED_Show_Click(frmMain.frmain.btnPatternW, null);       //显示255白画面，从255白画面开始调节
                        //Thread.Sleep(100);
                        //timeout = 0;
                    }
                    if ((GPN - index == 1) | (GPN - index == 2))//这里index最大值为绑点数量-1；倒数第2个绑点 以及倒数第3个绑点可以做技术处理
                    {
                        //GammaValue[0, 1] = 0;  GammaValue[0, 2] = 0;GammaValue[0, 0] = 0;     //0绑点不调，直接送零
                        GammaValue[GPN - index, 0] = (uint)(GammaValue[GPN - index + 1, 0] * (Point_VTDR6110C_ZCQ[GPN - index]) / (Point_VTDR6110C_ZCQ[GPN - index + 1]));  //绑点不调，直接赋值算了，如果有过度不均再手动修正即可
                        GammaValue[GPN - index, 1] = (uint)(GammaValue[GPN - index + 1, 1] * (Point_VTDR6110C_ZCQ[GPN - index]) / (Point_VTDR6110C_ZCQ[GPN - index + 1]));
                        GammaValue[GPN - index, 2] = (uint)(GammaValue[GPN - index + 1, 2] * (Point_VTDR6110C_ZCQ[GPN - index]) / (Point_VTDR6110C_ZCQ[GPN - index + 1]));
                        {   //写入Gamma，一共两处都要适配
                            CheckandCorrectGammaValue();
                            //GammaValueFormat_Click(null, null);
                            //显示当前(待)写入的Gamma寄存器值
                            txtGammaValue.Text = "R:" + GammaValue[GPN - index, 0] + "\r\n" + "G" + GammaValue[GPN - index, 1] + "\r\n" + "B" + GammaValue[GPN - index, 2] + "\r\n";
                            GammaValueSet((byte)index);
                            Thread.Sleep(100);
                            GammaValueSet((byte)index);
                            Thread.Sleep(100);
                            Application.DoEvents();//重点，必须加上，否则父子窗体都假死        
                        }
                        JumpGammaAdjustFlag = true;
                    }
                    //else if (GPN - index == 2) //倒数第2个绑点
                    //{
                    //}
                    else
                    {
                        if ((flag3 == 1) | (flag2 == 1) | (flag1 == 1))   //这个判断的意义可以猜猜看
                        {
                            {   //Gamma --R----
                                if (lumr > D_lums[GPN - index, 0])
                                {
                                    if ((!lastdirupR)) { timeout++; }
                                    if ((!lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                    GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] - rstep;// (byte)(int.Parse(numStep.Value.ToString()));
                                    lastdirupR = true;
                                }
                                else
                                {
                                    if ((lastdirupR)) { timeout++; }
                                    if ((lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                    GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] + rstep;
                                    lastdirupR = false;
                                }
                            }
                            {//Gamma ---G--
                                if (lumg > D_lums[GPN - index, 1])
                                {
                                    if ((!lastdirupG)) { timeout++; }
                                    if ((!lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                    GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] - gstep;
                                    lastdirupG = true;
                                }
                                else
                                {
                                    if ((lastdirupG)) { timeout++; }
                                    if ((lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                    GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] + gstep;
                                    lastdirupG = false;
                                }
                            }
                            {//--Gamma  ---B---
                                if (lumb > D_lums[GPN - index, 2])
                                {
                                    if ((!lastdirupB)) { timeout++; }
                                    if ((!lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                    GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] - bstep;
                                    lastdirupB = true;
                                }
                                else
                                {
                                    if ((lastdirupB)) { timeout++; }
                                    if ((lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                    GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] + bstep;
                                    lastdirupB = false;
                                }
                            }
                            //showmsg("rstep: " + rstep + "_gstetp: " + gstep + "_bstep: " + bstep);
                        }   //如果Gamma Value不在目标范围内，此处修正之
                        {//写入Gamma，一共两处都要适配
                            CheckandCorrectGammaValue();
                            //GammaValueFormat_Click(null, null);
                            //显示当前(待)写入的Gamma寄存器值
                            txtGammaValue.Text = "R:" + GammaValue[GPN - index, 0] + "\r\n" + "G" + GammaValue[GPN - index, 1] + "\r\n" + "B" + GammaValue[GPN - index, 2] + "\r\n";
                            GammaValueSet((byte)index);
                            Thread.Sleep(100);
                            Application.DoEvents();//重点，必须加上，否则父子窗体都假死        
                        } //写入Gamma，一共两处都要适配
                    }
                    if (!STOPAutoGammaFlag)
                        ;
                    else return;
                }
            }
            //TimTest.Stop();//停止计时
        }

        private void button1_Click(object sender, EventArgs e)
        {
            txttip.Clear();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (txttip.Text == string.Empty)
            {
                MessageBox.Show("内容为空!");
                return;
            }
            //创建保存对话框对象
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "gamma cfg files (*.txt)|*.txt"; //过滤文件类型
            save.FilterIndex = 1;
            save.RestoreDirectory = true;
            if (save.ShowDialog() == DialogResult.OK)
            {
                string path = save.FileName;
                save.DefaultExt = ".txt";
                StreamWriter sw = new StreamWriter(path);
                sw.WriteLine(txttip.Text);
                sw.Close();
            }
        }

        private void 恢复默认ToolStripMenuItem_Click(object sender, EventArgs e)//需要修改
        {
            VTDR6110C_ZCQ_Gamma_SetBox.Text = "REGW fe,80\r\n" +
                                                                    "REGW a0,00\r\n" +
                                                                    "REGW fe,22\r\n" +
                                                                    "REGW 06,00\r\n" +
                                                                    "REGW fe,00\r\n" +
                                                                    "REGW 53,20\r\n" +
                                                                    "__GAMMA_PAGE(FE,50)\r\n" +
                                                                    "__GAMMA_SET(0)\r\n" +
                                                                    "TUNING_SPEC(27, 600, 0.300, 0.315, 2.2)\r\n" +
                                                                    "LXY_SPEC(255, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(239, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(223, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(207, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(191, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(175, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(159, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(143, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(127, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(111, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(95, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(79, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(63, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(55, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(47, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(39, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(35, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(31, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(27, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(23, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(19, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(15, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(11, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(7, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(3, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(1, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(0, 0.002, 0.002, 0.05)\r\n" +
                                                                    "__GAMMA_TUNING\r\n" +
                                                                    "SAVE\r\n" +
                                                                    "\r\n" +
                                                                    "REGW fe,00\r\n" +
                                                                    "REGW fe,00\r\n" +
                                                                    "REGW fe,00\r\n" +
                                                                    "REGW 51,67\r\n" +
                                                                    "__GAMMA_PAGE(FE,60)\r\n" +
                                                                    "__GAMMA_SET(1)\r\n" +
                                                                    "TUNING_SPEC(27, 82, 0.300, 0.315, 2.2)\r\n" +
                                                                    "LXY_SPEC(255, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(239, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(223, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(207, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(191, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(175, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(159, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(143, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(127, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(111, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(95, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(79, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(63, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(55, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(47, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(39, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(35, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(31, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(27, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(23, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(19, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(15, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(11, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(7, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(3, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(1, 0.002, 0.002, 0.05)\r\n" +
                                                                    "LXY_SPEC(0, 0.002, 0.002, 0.05)\r\n" +
                                                                    "__GAMMA_TUNING\r\n" +
                                                                    "SAVE\r\n";
            Gamma_ads_R.Text = "0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2D,0x2F,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37";
            Gamma_ads_G.Text = "0x38,0x39,0x3A,0x3B,0x3D,0x3F,0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F,0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70";
            Gamma_ads_B.Text = "0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,0xA0,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7";
        }

        private void Text_Processing(string[] txt_path)
        {
            string[] arr = txt_path;
            {
                try
                {
                    Diven_Gamma.Clear();
                    Diven_Offset.Clear();
                    for (int i = 0; i < arr.Length; i++)
                    {
                        string line = arr[i];
                        line = line.Replace(" ", "");
                        if (line.Contains("TUNING_SPEC"))
                        {
                            line = line.Replace("TUNING_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr0 = line.Split(',');
                            Setting.Gamma_Property Gamma = new Setting.Gamma_Property(Convert.ToInt32(arr0[0]), Convert.ToDouble(arr0[1]), Convert.ToDouble(arr0[2]), Convert.ToDouble(arr0[3]), Convert.ToDouble(arr0[4]));
                            Diven_Gamma.Add(Gamma);
                        }
                        else if (line.Contains("LXY_SPEC"))
                        {
                            line = line.Replace("LXY_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr1 = line.Split(',');
                            //将Offset对象放入集合
                            Setting.Offset_Property Offset = new Setting.Offset_Property(Convert.ToInt32(arr1[0]), Convert.ToDouble(arr1[1]), Convert.ToDouble(arr1[2]), Convert.ToDouble(arr1[3]));
                            Diven_Offset.Add(Offset);
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("格式输入有误");
                }
            }
            try  //获取调整spec
            {
                numVT_loff.Text = Diven_Offset[0].LUM_OFF.ToString();
                txtVT_xoff.Text = Diven_Offset[0].X_OFF.ToString();
                txtVT_yoff.Text = Diven_Offset[0].Y_OFF.ToString();

                Total_points = Diven_Gamma[0].Points_num;
                D_lums = new double[Total_points, 3];
                D_lum = new double[Total_points];
                Point_VTDR6110C_ZCQ = new int[Total_points];

                txtVT_gamma.Text = Diven_Gamma[0].Curve.ToString();
                txtVT_lum.Text = Diven_Gamma[0].Lum.ToString();
                txtVT_x.Text = Diven_Gamma[0].X.ToString();
                txtVT_y.Text = Diven_Gamma[0].Y.ToString();

                D_x = Convert.ToDouble(txtVT_x.Text);  //获取调节目标色坐标 x
                D_y = Convert.ToDouble(txtVT_y.Text); ////获取调节目标色坐标 y
                Lr_d = R_y * ((D_y - G_y) * (B_x - D_x) + (D_x - G_x) * (D_y - B_y)) / B_y / ((D_y - G_y) * (D_x - R_x) + (D_x - G_x) * (R_y - D_y));
                Lb_d = 1.0;
                Lg_d = G_y * ((D_y - R_y) * (B_x - D_x) + (D_x - R_x) * (D_y - B_y)) / B_y / ((D_y - R_y) * (D_x - G_x) + (D_x - R_x) * (G_y - D_y));

                for (int i = 0; i < Total_points; i++)
                {   //Diven_Offset[p].NO 灰阶绑点                 
                    D_lum[Total_points - i - 1] = (Math.Pow((Diven_Offset[i].NO / 255.0), Diven_Gamma[0].Curve) * Diven_Gamma[0].Lum); //每绑点目标亮度
                    D_lums[Total_points - i - 1, 0] = D_lum[Total_points - i - 1] * Lr_d / (Lr_d + Lg_d + Lb_d);
                    D_lums[Total_points - i - 1, 1] = D_lum[Total_points - i - 1] * Lg_d / (Lr_d + Lg_d + Lb_d);
                    D_lums[Total_points - i - 1, 2] = D_lum[Total_points - i - 1] * Lb_d / (Lr_d + Lg_d + Lb_d);
                    Point_VTDR6110C_ZCQ[Total_points - i - 1] = Diven_Offset[i].NO;
                }

            }
            catch
            {
                MessageBox.Show("格式输入有误");
            }
        }

        private void btnGammaValueUpdate_Click(object sender, EventArgs e)      //刷新UI上表格内的Gamma数据
        {
            int Line_Count = 0;
            try
            {
                Line_Count = GammaReg_dataGridView.RowCount;
            }
            catch
            {
                MessageBox.Show("表格数据(行数)异常！", "提示：");
                return;
            }
            try
            {
                for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                {
                    GammaValue[i, 0] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[2].Value);
                    GammaValue[i, 1] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[3].Value);
                    GammaValue[i, 2] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[4].Value);
                }
                //MessageBox.Show("数据更新OK！", "提示：");                
                showmsg("Gamma数据更新OK！");
            }
            catch
            {
                MessageBox.Show("Gamma数据更新错误！", "唐韬说：");
            }
        }

        private void Msr_CA310()
        {
            frmMain.frmain.Msr_CASDK();
            auto_lum = frmMain.frmain.CASDK_LUM;
            auto_x = frmMain.frmain.CASDK_x;
            auto_y = frmMain.frmain.CASDK_y;
        }   //获取CA310/CA410读数
        private void btnVTStop_Click(object sender, EventArgs e)
        {
            STOPAutoGammaFlag = true;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
            //TimTest.Stop();//停止计时
            frmMain.frmain.textBox1.ForeColor = Color.Black;
            //btnCalculateRM692G3.PerformClick();
        }

        private void btnSaveGamma_Click(object sender, EventArgs e)
        {
            {
                Button btnTmp = (Button)sender;
                switch (btnTmp.Name)
                {
                    case "btnSaveGamma":
                        {
                            {//保存
                                //SaveFileDialog sf = new SaveFileDialog(); //对话框
                                //sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型
                                string str = "灰阶序号,灰阶亮度,reg_R,reg_G,reg_B\r\n";
                                //if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                                {
                                    //if (sf.FileName == "") return; //如果没有输入文件名
                                    try
                                    {
                                        StreamWriter sw = null; //文件流
                                        string fname = Application.StartupPath + @"\l_gamma\VTDR6110C_ZCQGamma" + GammaBandSelect.Text + ".csv";
                                        sw = new StreamWriter(fname, false, Encoding.UTF8);
                                        for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                        {
                                            str = str + this.GammaReg_dataGridView.Rows[i].Cells[0].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString() + "\r\n";
                                        }
                                        sw.WriteLine(str);
                                        sw.Dispose(); //释放资源
                                        sw.Close(); //关闭数据流
                                        //MessageBox.Show("数据保存OK！", "系统提示：");
                                        showmsg("----数据保存OK----");
                                        showmsg("保存路径:" + fname);
                                    }
                                    catch
                                    {
                                        MessageBox.Show("数据保存时发生错误，请再试！", "系统提示：");
                                    }
                                }
                            }
                        }
                        break;
                    case "btnLoadGamma":
                        {
                            this.GammaReg_dataGridView.Rows.Clear();
                            //OpenFileDialog sf = new OpenFileDialog();
                            int Line_Count = 0;
                            string strtmp = "";
                            //sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义文件的类型
                            //sf.Title = "数据导入";
                            //if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                            {
                                string fname = Application.StartupPath + @"\l_gamma\VTDR6110C_ZCQGamma" + GammaBandSelect.Text + ".csv";
                                if (!File.Exists(fname))
                                {
                                    showmsg(fname + "文件不存在 ");
                                    return;
                                }
                                FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
                                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                                string strLine = streamReader.ReadLine();
                                while (!string.IsNullOrEmpty(strLine))
                                {
                                    strtmp = strtmp + strLine + ",";
                                    strLine = streamReader.ReadLine(); //循环读取下一行
                                    Line_Count++;
                                }
                                fs.Close(); //关闭流
                                streamReader.Close();
                                string[] arrtmp = strtmp.Split(new Char[] { ',' });
                                for (int j = 1; j <= Line_Count - 1; j++)
                                {
                                    DataGridViewRow Row1 = new DataGridViewRow();
                                    GammaReg_dataGridView.Rows.Add(Row1);
                                }
                                try
                                {
                                    showmsg("Gamma数据导入路径: " + fname);
                                    for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                                    {
                                        GammaReg_dataGridView.Rows[i].Cells[0].Value = arrtmp[5 * (i + 1) + 0];
                                        GammaReg_dataGridView.Rows[i].Cells[1].Value = arrtmp[5 * (i + 1) + 1];
                                        GammaReg_dataGridView.Rows[i].Cells[2].Value = arrtmp[5 * (i + 1) + 2];
                                        GammaReg_dataGridView.Rows[i].Cells[3].Value = arrtmp[5 * (i + 1) + 3];
                                        GammaReg_dataGridView.Rows[i].Cells[4].Value = arrtmp[5 * (i + 1) + 4];
                                    }
                                    showmsg("Gamma数据 " + GammaBandSelect.Text + "  导入OK！");
                                }
                                catch
                                {
                                    MessageBox.Show("Gamma数据导入时发生错误！", "提示：");
                                }
                            }
                        }
                        break;
                    case "btn_CAS200_Clean":
                        {
                            DialogResult dr = MessageBox.Show("确认清空列表数据吗？", "系统提示", MessageBoxButtons.OKCancel);
                            if (dr == DialogResult.OK)
                            {
                                this.GammaReg_dataGridView.Rows.Clear();
                            }
                        }
                        break;

                    default: break;
                }
            }
        }
    }
}
